#!/bin/env python3
# -*- coding:utf-8 -*-
"""
    [模块名]
    Add By : cdj <e4ting@qq.com> 2021-07-14 17:57:18
"""
from flask_restful          import Resource
from flask                  import request
from e4ting                 import util,log
# from common.utilredis       import NewID
from e4ting.cache           import UUIDCache,FrpCache
from e4ting.task            import Async
# from bin.master             import Master

class WebFRP(Resource):

    def get_or_alloc(self, uuid):
        log.info(uuid)
        cache = UUIDCache(uuid)
        if not cache.exists():
            return dict(code=404, data=None)

        port = cache.frp_port
        if port:
            return dict(code=200, port=int(port))

        frp = FrpCache(uuid)
        port = frp.port
        if port:
            cache.frp_port = port
            return dict(code=200, port=int(port))

        # 缓存中都找不到，就新建一个端口
        port = FrpCache.frp_port
        cache.frp_port = port
        frp.set(port=port, **request.headers)
        return dict(code=200, port=port)

    def get(self, id=None):
        """ 分配FRP端口 """
        uuid = id or request.args.get("uuid", None)
        return self.get_or_alloc(uuid)

    def post(self, id=None):
        """ 分配FRP端口 """
        uuid = id or request.json.get("uuid", None)
        ret = self.get_or_alloc(uuid)
        Async().push_frp(uuid)
        return ret



